package com.lepu.app.usercenter.fragment;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.usercenter.ForgetPwdActivity;
import com.lepu.app.usercenter.bean.BeanPwdQuestion;
import com.lepu.app.usercenter.util.UserCenterUtil;
import com.lepu.pasm.R;

public class FragmentPwdQuestion extends BaseFragment implements AsyncRequest {

	private static final String REQUEST_OK = "request_ok";
	private static final String REQUEST_OK_2 = "request_ok_2";

	private static final int MSG_OK_SUCCESS = 10;
	private static final int MSG_OK_FAIL = 11;

	private static final int MSG_OK_2_SUCCESS = 20;
	private static final int MSG_OK_2_FAIL = 21;
	private static final int MSG_OK_2_ANSWR_ERROR = 22;

	private View mMainView = null;
	private boolean mInitDataSuccess = false;// 是否加载完数据

	private LinearLayout mFirstLayout = null;
	private ScrollView mSecondScrollView = null;
	private TextView mPhoneTextView = null;
	
	private String mQuestion0Id = "0";
	private String mQuestion1Id = "0";

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMainView = LayoutInflater.from(getActivity()).inflate(
				R.layout.usercenter_forget_pwd_fragment_question, null, false);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				// 第一次进入页面获取数据
				mInitDataSuccess = true;
			}
		}
	}

	/*
	 * 初始化ui控件，不要初始化数据！！！！
	 * 
	 * 初始化控件，需要用mMainView.findViewById 不能使用findViewById，否则程序会闪退的
	 */
	private void init() {
		mFirstLayout = (LinearLayout) mMainView.findViewById(R.id.firstLayout);
		mSecondScrollView = (ScrollView) mMainView
				.findViewById(R.id.secondScrollView);

		mPhoneTextView = (TextView) mMainView.findViewById(R.id.phoneTextView);
		Button firstOkButton = (Button) mMainView
				.findViewById(R.id.firstOkButton);
		Button secondOkButton = (Button) mMainView
				.findViewById(R.id.secondOkButton);

		firstOkButton.setOnClickListener(mOnClickListener);
		secondOkButton.setOnClickListener(mOnClickListener);
		
		EditText questionEditText1 = (EditText) mMainView.findViewById(R.id.questionEditText1);
		EditText questionEditText2 = (EditText) mMainView.findViewById(R.id.questionEditText2);
		
		questionEditText1.setFilters(new InputFilter[]{new EmojiFilter()});
		questionEditText2.setFilters(new InputFilter[]{new EmojiFilter()});
		
		mSecondScrollView.setOnTouchListener(new View.OnTouchListener() {
			
			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				UtilityBase.closeSoftInput(getActivity());
				return false;
			}
		});
	}

	private void requestOk() {
		EditText userEditText = (EditText) mMainView.findViewById(R.id.userEditText);
		String userContent = userEditText.getText().toString().trim();

		boolean flag = UserCenterUtil.getPwdQuestionByPhone(getActivity(), this,
				REQUEST_OK, userContent);
		if (flag) {
			ForgetPwdActivity.getInstance().showProgressDialog();
		}
	}

	private void requestOk2() {

//		TextView questionTextView1 = (TextView) mMainView
//				.findViewById(R.id.questionTextView1);
//		TextView questionTextView2 = (TextView) mMainView
//		.findViewById(R.id.questionTextView2);
		EditText questionEditText1 = (EditText) mMainView.findViewById(R.id.questionEditText1);
		EditText questionEditText2 = (EditText) mMainView.findViewById(R.id.questionEditText2);

		EditText pwdEditText = (EditText) mMainView.findViewById(R.id.pwdEditText);
		EditText pwdEditText2 = (EditText) mMainView.findViewById(R.id.pwdEditText2);

		String userContent = mPhoneTextView.getText().toString().trim();

		//String question1 = questionTextView1.getText().toString().trim();
		String answer1 = questionEditText1.getText().toString().trim();
		//String question2 = questionTextView2.getText().toString().trim();
		String answer2 = questionEditText2.getText().toString().trim();

		String pwdContent = pwdEditText.getText().toString().trim();
		String pwdContent2 = pwdEditText2.getText().toString().trim();

		boolean flag = UserCenterUtil.getResetPwdByPwdQuestion(getActivity(),
				this, REQUEST_OK_2, userContent, pwdContent, pwdContent2,
				mQuestion0Id, answer1, mQuestion1Id, answer2);
		if (flag) {
			ForgetPwdActivity.getInstance().showProgressDialog();
		}
	}

	private View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.firstOkButton:
				requestOk();
				break;
			case R.id.secondOkButton:

				requestOk2();
				break;

			default:
				break;
			}
		}
	};

	private void okSuccess(ArrayList<BeanPwdQuestion> dataList) {

		
		if (dataList != null && dataList.size() > 0) {
			mFirstLayout.setVisibility(View.GONE);
			mSecondScrollView.setVisibility(View.VISIBLE);

			EditText userEditText = (EditText) mMainView.findViewById(R.id.userEditText);
			String userContent = userEditText.getText().toString().trim();

			mPhoneTextView.setText(userContent);

			TextView questionTextView1 = (TextView) mMainView
					.findViewById(R.id.questionTextView1);
			TextView questionTextView2 = (TextView) mMainView
					.findViewById(R.id.questionTextView2);

			mQuestion0Id = dataList.get(0).SQID;
			mQuestion1Id = dataList.get(1).SQID;
			
			questionTextView1.setText(dataList.get(0).Question);
			questionTextView2.setText(dataList.get(1).Question);

		} else {
			// 未设置密保问题
			new MyDialog(getActivity())
					.setMessage("未设置密保问题，请使用其它方式找回!")
					.setNegativeButtonSplitImageHide(true)
					.setPositiveButton(R.string.app_ok,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {

								}
							}).create(null).show();
		}
	}

	private void ok2Success() {
		new MyDialog(getActivity())
				.setMessage("新密码设置成功").setCancelable(false)
				.setCanceledOnTouchOutside(false)
				.setNegativeButtonSplitImageHide(true)
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						LoginUtil.jumpLogin(ForgetPwdActivity
								.getInstance());

						ForgetPwdActivity.getInstance().finish(true);
					}
				}).create(null).show();
	}
	
	private void ok2AnswerError() {
		StringBuffer sb = new StringBuffer();
		sb.append("忘记密码了吗？再想想。想不出请尝试手机找回或人工帮助。");
		
		new MyDialog(getActivity())
				.setMessage(sb.toString()).setCancelable(false)
				.setCanceledOnTouchOutside(false)
				.setNegativeButtonSplitImageHide(true)
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {

					}
				}).create(null).show();
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_OK_SUCCESS:
				ForgetPwdActivity.getInstance().hideProgressDialog();
			
				@SuppressWarnings("unchecked")
				ArrayList<BeanPwdQuestion> dataList = (ArrayList<BeanPwdQuestion>) msg.obj;

				okSuccess(dataList);

				break;
			case MSG_OK_FAIL:
				ForgetPwdActivity.getInstance().hideProgressDialog();
				
				int code = msg.arg1;
				if(code == 2)
				{
					okSuccess(null);
				}
				break;
			case MSG_OK_2_SUCCESS:
				ForgetPwdActivity.getInstance().hideProgressDialog();

				ok2Success();
				break;
			case MSG_OK_2_ANSWR_ERROR:
				ForgetPwdActivity.getInstance().hideProgressDialog();
				
				ok2AnswerError();
				break;
			case MSG_OK_2_FAIL:
				ForgetPwdActivity.getInstance().hideProgressDialog();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_OK)) {
			ArrayList<BeanPwdQuestion> dataList = BeanPwdQuestion.parseJsonData((String) data);
			Message msg = mHandler.obtainMessage();
			msg.obj = dataList;
			msg.what = MSG_OK_SUCCESS;
			mHandler.sendMessage(msg);

		} else if (object.equals(REQUEST_OK_2)) {
			String result = (String) data;
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (code == 200) {
				mHandler.sendEmptyMessage(MSG_OK_2_SUCCESS);
			} else{
				mHandler.sendEmptyMessage(MSG_OK_2_FAIL);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_OK)) {
			
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(errorMessage);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			Message msg = mHandler.obtainMessage();
			msg.arg1 = code;
			msg.what = MSG_OK_FAIL;
			mHandler.sendMessage(msg);
			
		} else if (object.equals(REQUEST_OK_2)) {
			
			String result = (String) errorMessage;
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if(code == 112){
				mHandler.sendEmptyMessage(MSG_OK_2_ANSWR_ERROR);
			}else{
				mHandler.sendEmptyMessage(MSG_OK_2_FAIL);
			}
			
		}
	}
}
